package springboot.study.project.util.common;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 通过工具类
 *
 * @author baoxia
 */
public class Util {

    private static final Logger logger = LoggerFactory.getLogger(Util.class); // 日志打印

    /**
     * 将对象转化为int，如果不能转化，则返回0
     *
     * @param obj
     * @return int
     */
    public static int getIntOfObj(Object obj) {
        if (obj == null || "".equals(obj)) {
            return 0;
        }
        try {
            return Math.round(Float.valueOf(obj.toString().trim()));
        } catch (Exception e) {
            //logger.error("正确数据类型应为java.lang.Integer_实际接收数据为_"+e.getMessage());
        }
        return 0;
    }

    /**
     * 将对象转化为long，如果转化不了则返回0
     *
     * @param obj
     * @return Long
     */
    public static Long getLongOfObj(Object obj) {
        if (obj == null || "".equals(obj)) {
            return new Long(0);
        }
        try {
            return Math.round(Double.valueOf(obj.toString()));
        } catch (Exception e) {
            //logger.error("正确数据类型应为java.lang.Long_实际接收数据为_"+e.getMessage());
        }
        return new Long(0);
    }

    /**
     * 将对象转化为float，如果转化不了则返回0
     *
     * @param flo
     * @return
     */
    public static float getFloatOfObj(Object flo) {
        if (flo == null || flo.equals("")) {
            return 0f;
        }
        if (flo instanceof Float) {
            return ((Float) flo).floatValue();
        }
        if (isNumber(flo)) {
            return Float.parseFloat(flo.toString());
        }
        return 0f;
    }

    /**
     * 将对象转化为double，如果转化不了则返回0
     *
     * @param dou
     * @return
     */
    public static double getDoubleOfObj(Object dou) {
        if (dou == null || dou.equals("")) {
            return 0;
        }
        if (dou instanceof Double) {
            return ((Double) dou).doubleValue();
        }
        if (isNumber(dou)) {
            return Double.parseDouble(dou.toString().trim());
        }
        if (dou.toString().substring(0, 1).equals(".")) {
            StringBuilder num = new StringBuilder("0");
            num.append(dou.toString());
            return new Double(num.toString());
        }
        return 0;
    }


    /**
     * Object转String，如果对象为null，则返回""
     *
     * @param obj
     * @return
     */
    public static String getStrOfObj(Object obj) {
        if (obj == null) {
            return "";
        }
        return obj.toString();
    }

    /**
     * 将null的对象转换为""
     *
     * @param obj
     * @return String
     */
    public static String getNullStr(Object obj) {
        if (obj == null) {
            return "";
        }

        if ("null".equals(obj) || "NULL".equals(obj)) {
            return "";
        } else {
            return obj.toString();
        }
    }

    /**
     * 判断某字符串是否是纯数字,如“12345”或“100.222”
     *
     * @param string
     * @return boolean
     */
    public static boolean isNumber(Object string) {
        String regex = "-?\\d+\\.?\\d*";
        String str = String.valueOf(string).trim();
        if (str.endsWith(".")) {
            return false;
        }
        if (str.matches(regex)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断某字符串是否是纯数字,如“3.6407488E8”或“1.73496E9”（带科学计数法）
     *
     * @param string
     * @return boolean
     */
    public static boolean isNumberByE(Object string) {
        String regex = "[+-]?[\\d]+([\\.][\\d]+)?([Ee][+-]?[\\d]+)?";
        String str = String.valueOf(string).trim();
        if (str.endsWith(".")) {
            return false;
        }
        if (str.matches(regex)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Object转List
     */
    @SuppressWarnings("unchecked")
    public static <T> List<T> getListOfObj(Object obj) {
        try {
            if (obj == null) {
                return new ArrayList<T>();
            } else {
                return (List<T>) obj;
            }
        } catch (Exception ingore) {
            return new ArrayList<T>();
        }
    }

    /**
     * Object转Map
     */
    public static <K, V> Map<K, V> getMapOfObj(Object obj) {
        try {
            if (obj == null) {
                return new HashMap<K, V>();
            } else {
                return (Map<K, V>) obj;
            }
        } catch (Exception ingore) {
            return new HashMap<K, V>();
        }
    }

    /**
     * json 转为 List<Map<String, Object>>
     *
     * @param json
     * @return
     */
    public static List<Map<String, Object>> jsonToListMap(String json) {
        if (StringUtil.isBlank(json)) {
            return new ArrayList<Map<String, Object>>();
        }
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        List<Object> list = JSON.parseArray(json);
        for (Object object : list) {
            if (StringUtil.isBlank(object)) {
                continue;
            }
            // Map<String, Object> ret = (Map<String, Object>) object;// 取出list里面的值转为map
            Map<String, Object> ret = JSON.parseObject(object.toString(), Map.class);// 取出list里面的值转为map
            result.add(ret);
        }
        return result;
    }

    /**
     * 将预编译的sql改为带参数据的可执行sql
     *
     * @param sql
     * @param values
     * @return
     */
    public static String putSqlParams(String sql, List<Object> values) {
        StringBuffer sb = new StringBuffer();
        Pattern p = Pattern.compile("\\?");
        Matcher matcher = p.matcher(sql);
        int index = 0;
        while (matcher.find()) {
            matcher.appendReplacement(sb, "'" + Util.getStrOfObj(values.get(index)) + "'");
            index++;
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /**
     * 获取插入数据的sql
     *
     * @param tableName
     * @param dataMap
     * @return
     */
    public static String getSql(String tableName, Map<String, Object> dataMap) {
        if (dataMap == null || dataMap.size() <= 0) {
            return null;
        }

        StringBuffer keyStr = new StringBuffer("(");
        StringBuffer valueStr = new StringBuffer("(");
        for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
            String fieldName = entry.getKey();

            keyStr.append(fieldName + ",");
            valueStr.append("?,");
        }

        StringBuffer result = new StringBuffer("replace into ").append(tableName)
                .append(keyStr.substring(0, keyStr.length() - 1) + ")").append(" values")
                .append(valueStr.substring(0, valueStr.length() - 1) + ")");

        return result.toString();
    }

    public static String getSqlByInsertUpdate(String tableName, Map<String, Object> dataMap) {
        if (dataMap == null || dataMap.size() <= 0) {
            return null;
        }

        StringBuffer insertKeyStr = new StringBuffer("(");
        StringBuffer insertValueStr = new StringBuffer("(");
        StringBuffer updatevalueStr = new StringBuffer("");
        for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
            String fieldName = entry.getKey();

            insertKeyStr.append(fieldName + ",");
            insertValueStr.append("?,");
            updatevalueStr.append(fieldName + "=?,");
        }

        StringBuffer result = new StringBuffer("insert into ").append(tableName)
                .append(insertKeyStr.substring(0, insertKeyStr.length() - 1) + ")").append(" values")
                .append(insertValueStr.substring(0, insertValueStr.length() - 1) + ")")
                .append(" on duplicate key update ")
                .append(updatevalueStr.substring(0, updatevalueStr.length() - 1));

        return result.toString();
    }

    /**
     * 单个数据Map获取data
     *
     * @param dataMap
     * @return
     */
    public static List<Object> getValues(Map<String, Object> dataMap) {
        return new ArrayList<Object>(dataMap.values());
    }

    public static List<Object> getValues2(Map<String, Object> dataMap) {
        List<Object> values = new ArrayList<Object>();
        values.addAll(dataMap.values());
        values.addAll(dataMap.values());
        return values;
    }

    /**
     * 批量获取data
     *
     * @param dataList
     * @return
     */
    public static List<List<Object>> getBatchInsertData(List<Map<String, Object>> dataList, int paramSize) {
        List<List<Object>> valuesList = new ArrayList<List<Object>>();

        for (Map<String, Object> dataMap : dataList) {
            List<Object> values = new ArrayList<Object>(dataMap.values());
            if (values.size() == paramSize) {
                valuesList.add(values);
            } else {
                logger.warn("请求的结果字段数量与SQL预编译数量不符合--->" + JSON.toJSONString(values));
                logger.warn("正确请求结果--->" + (valuesList.size() > 0 ? JSON.toJSONString(valuesList.get(0)) : ""));
                logger.warn("错误请求结果--->" + JSON.toJSONString(values));
            }
        }
        return valuesList;
    }

    public static List<List<Object>> getBatchInsertDataByInsertUpdate(List<Map<String, Object>> dataList) {
        List<List<Object>> valuesList = new ArrayList<List<Object>>();

        for (Map<String, Object> dataMap : dataList) {
            List<Object> values = new ArrayList<Object>();
            values.addAll(dataMap.values());
            values.addAll(dataMap.values());
            valuesList.add(values);
        }
        return valuesList;
    }
}
